%------------------------------------------------------------------
%------------------------------------------------------------------
%   Author: Md. Sazzad Hussain (sazzad.hussain@sydney.edu.au)
%   Learning and Affect Technologies Engineering
%   University of Sydney, 2012
%------------------------------------------------------------------
%------------------------------------------------------------------

% %%Sync & Feature Extraction Program (IAPS Physio Data)
%channels: ECG, EMG, GSR, Resp
function [featExt]=iapsFeatEx(subjectID,filesPath,sTime,winSizeECG,winSizeResp,sRate,dSample,featdir,dubug,opSys)

warning off all;

if opSys==1
    sep='/';
elseif opSys==2
    sep='\';
end

filesDir=dir(filesPath);%dir info for files path
x=1;
for m=1:length(filesDir)
    [path,name,ext,ver] = fileparts(filesDir(m).name);
    for n=1:length(subjectID(:,1))
        if strncmp(subjectID(n,:),name,27)%choose only selected subjects
            if strcmp(ext,'.mat')%.mat files
                loadPhysio(x,:)=[filesPath sep name ext];%.mat physio path
                physioSplit(x,:)= regexp(name,'_','split');
                physioATS=physioSplit(:,5);%physio abs time stamp
                %                 x=x+1;
            elseif strcmp(ext, '.txt')%.txt files
                loadAnn(x,:)=[filesPath sep name ext];%.txt annotation path
                x=x+1;
            end
        end
    end
end

mkdir(featdir);%create directory for features (.mat)
for j=1:(x-1)
    load(loadPhysio(j,:));%load physio file

    data=downsample(data,dSample);%-->down sample all physio channels
    nsRate=(sRate/dSample);%new sample rate
    dataEDR = edr_extract(data(:,1), nsRate);%derive rsp from ecg
    
    fid = fopen(loadAnn(j,:));%load annotation
    C = textscan(fid,'%s%s%s%s%f%s','delimiter', ',');
    fclose(fid);
%     subjectFeatDir=[featdir '\' subjectID(j,:)];
%     mkdir(subjectFeatDir);%create directory for features

    Absolute_Time = datenum(physioATS(j), 'HH-MM-SS')*24*60*60; %in seconds
    
    start_times = C{3};
    k = 2;
    featmat = [];
    featmatECG = [];
    featmatRESP = [];
    featmatEDR = [];
    valCatVec=[];
    arCatVec=[];
    dimCatVec=[];
    valSelfVec=[];
    arSelfVec=[];
    dimSelfVec=[];
    
    lenPhysio=length(data);%length of physio data
    
    while k <= length (start_times)-1
        Start_Trial = datenum(start_times{k},'HH:MM:SS')*24*60*60; % in seconds
        Start_Index = ((Start_Trial + sTime) - Absolute_Time) * nsRate; %start time
               
        End_IndexECG = (Start_Index + winSizeECG * nsRate)-1;%end time for ecg window
        End_IndexResp = (Start_Index + winSizeResp * nsRate)-1;%end time for resp window
        
        if lenPhysio<max([End_IndexECG End_IndexResp])
            break;
        end
        
        Trial_ChunkECG = data(Start_Index:End_IndexECG,1); %ECG chunk
        Trial_ChunkResp = data(Start_Index:End_IndexResp,6); %RSP chunk
        Trial_ChunkEDR = dataEDR(Start_Index:End_IndexResp); %EDR chunk
        
        if dubug==1
            %plot channels
            pause(1)
            subplot(3,1,1),plot(Trial_ChunkECG);
            subplot(3,1,2),plot(Trial_ChunkResp);
            subplot(3,1,3),plot(Trial_ChunkEDR);
        end
        
        ecgAffect= Trial_ChunkECG;%ecg data
        respAffect= Trial_ChunkResp;%resp data
        edrAffect= Trial_ChunkEDR;%resp data
        
        %feature extraction
        [ECGfeatvc ECGfeatnames RESPfeatvc RESPfeatnames EDRfeatvc EDRfeatnames]...
            = aubtProxy_edr(ecgAffect, respAffect, edrAffect, nsRate);
        
        featvc = [ECGfeatvc,RESPfeatvc,EDRfeatvc];
        featmat = [featmat;featvc];
        
        %featmat individual for channels
        featvcECG=[ECGfeatvc];
        featmatECG=[featmatECG;featvcECG];
        featvcRESP=[RESPfeatvc];
        featmatRESP=[featmatRESP;featvcRESP];
        featvcEDR=[EDRfeatvc];
        featmatEDR=[featmatEDR;featvcEDR];
        
        %extracting theoretical categories
        splitCat=regexp(C{2}(k),'_','split');
        valCat=splitCat{:}(2);
        arCat=splitCat{:}(3);
        dimCat=strcat(valCat,'-',arCat);
        valCatVec = [valCatVec;valCat];
        arCatVec = [arCatVec;arCat];
        dimCatVec = [dimCatVec;dimCat];
        
        %extracting self reports
        switch C{5}(k)
            case 1
                valSelf={'MediumValence'};
                arSelf={'LowArousal'};
                dimSelf={'MediumValence-LowArousal'};
            case 2
                valSelf={'HighValence'};
                arSelf={'LowArousal'};
                dimSelf={'HighValence-LowArousal'};
            case 3
                valSelf={'MediumValence'};
                arSelf={'MediumArousal'};
                dimSelf={'MediumValence-MediumArousal'};
            case 4
                valSelf={'HighValence'};
                arSelf={'MediumArousal'};
                dimSelf={'HighValence-MediumArousal'};
            case 5
                valSelf={'HighValence'};
                arSelf={'HighArousal'};
                dimSelf={'HighValence-HighArousal'};
            case 6
                valSelf={'MediumValence'};
                arSelf={'HighArousal'};
                dimSelf={'MediumValence-HighArousal'};
            case 7
                valSelf={'LowValence'};
                arSelf={'HighArousal'};
                dimSelf={'LowValence-HighArousal'};
            case 8
                valSelf={'LowValence'};
                arSelf={'MediumArousal'};
                dimSelf={'LowValence-MediumArousal'};
            case 9
                valSelf={'LowValence'};
                arSelf={'LowArousal'};
                dimSelf={'LowValence-LowArousal'};
        end
        valSelfVec = [valSelfVec;valSelf];
        arSelfVec = [arSelfVec;arSelf];
        dimSelfVec = [dimSelfVec;dimSelf];
        subjectID(j,:)
        k = k+ 1
    end
    featmat = num2cell(featmat);
    featMatClass = [featmat,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featnames = [ECGfeatnames,RESPfeatnames,strcat('edr_',EDRfeatnames),...
        'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];       
    
    data_set = [featnames;featMatClass];    
%         CELL2CSV([featdir,sep,subjectID(j,:),'_all.csv'],data_set,',');
    
    %save for individual channels
    featmatECG = num2cell(featmatECG);
    featmatRESP = num2cell(featmatRESP);
    featmatEDR = num2cell(featmatEDR);
    
    featMatClassECG = [featmatECG,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featMatClassRESP = [featmatRESP,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featMatClassEDR = [featmatEDR,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    
    featnamesECG = [ECGfeatnames,'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    featnamesRESP = [RESPfeatnames,'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    featnamesEDR = [strcat('edr_',EDRfeatnames),'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    
    data_setECG = [featnamesECG;featMatClassECG];
    data_setRESP = [featnamesRESP;featMatClassRESP];
    data_setEDR = [featnamesEDR;featMatClassEDR];
    
    ECGDir=[featdir sep 'ECG_Feat' sep num2str(sTime) '-' num2str(winSizeECG)];
    RespDir=[featdir sep 'Resp_Feat' sep num2str(sTime) '-' num2str(winSizeResp)];
    EDRDir=[featdir sep 'EDR_Feat' sep num2str(sTime) '-' num2str(winSizeResp)];
    mkdir(ECGDir);
    mkdir(RespDir);
    mkdir(EDRDir);
    
    %save ECG
    CELL2CSV([ECGDir,sep,subjectID(j,:),'_ecg_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setECG,',');
    %save Resp
    CELL2CSV([RespDir,sep,subjectID(j,:),'_resp_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setRESP,',');
    %save EDR
    CELL2CSV([EDRDir,sep,subjectID(j,:),'_edr_',num2str(sTime),'-',num2str(winSizeECG),'.csv'],data_setEDR,',');
end
clear all;
featExt=1;




